﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using AIPrakt05;
using RVO;
using System.ComponentModel;
using System.Windows.Threading;

namespace AgentGUI
{
    /// <summary>
    /// Interaktionslogik für MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        AgentSimulator simulator;
        BackgroundWorker worker;
        UpdateProgressDelegate update;
        int renderCounter=0;
        IList<Ellipse> agentsList;

        public MainWindow()
        {
            InitializeComponent();
            Console.WriteLine("Start App!");
            agentsList = new List<Ellipse>();
            simulator = new AgentSimulator();
            simulator.SimulationChangedEvent += UpdateGUI;
            
            Random random = new Random();

            for (int i = 0; i < simulator.Sim.getNumAgents(); i++)
            {
                Ellipse e = new Ellipse();
                e.Width = 15; e.Height = 15;
                
                if (i < 75)
                {
                    e.Fill = new SolidColorBrush(Color.FromRgb((byte)random.Next(0,255), (byte)random.Next(0,255),(byte) random.Next(0,255)));
                } if (i < 51)
                {
                    e.Fill = new SolidColorBrush(Color.FromRgb(119, 185, 0));
                } if(i < 17)
                {
                    e.Fill = new SolidColorBrush(Color.FromRgb(175,175,175));
                }
                agentsList.Add(e);
                myCanvas.Children.Add(e);
            }

            startSimInThread();
            update = new UpdateProgressDelegate(UpdateProgressAgents);
        }

        private void startSimInThread()
        {
            worker = new BackgroundWorker();
            worker.DoWork += delegate
            {
                simulator.RunSimulation();
            };
            worker.RunWorkerAsync();
        }

        public delegate void UpdateProgressDelegate(int agent, float x, float y);

        public void UpdateProgressAgents(int agent, float x, float y)
        {
            Canvas.SetLeft(agentsList[agent], x);
            Canvas.SetTop(agentsList[agent], y);
        }

        private void UpdateGUI(Simulator sim)
        {
            if (renderCounter % 10 == 0)
            {
                for (int i = 0; i < simulator.Sim.getNumAgents(); i++)
                {
                    Vector2 pos = sim.getAgentPosition(i);
                    this.Dispatcher.BeginInvoke(update, i, pos.x(), pos.y());
                }
            }
            renderCounter++;
        }
    }
}
